package com.shawn.baseappbygroovydsl.net

import com.shawn.baseappbygroovydsl.BuildConfig
import com.shawn.baseappbygroovydsl.utils.UtilCommon
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.converter.scalars.ScalarsConverterFactory
import java.net.Proxy
import java.util.concurrent.TimeUnit

/**
 * 描述：
 * 作者： shawn
 * 时间： 2024/9/2518:44
 */
class Api {
    companion object {
        private const val CONNECT_TIME_OUT: Long = 15000
        private const val READ_TIME_OUT: Long = 15000
        private const val WRITE_TIME_OUT: Long = 15000

        private fun initOKHttpClient() = run {
            val builder = OkHttpClient.Builder()
            builder.proxy(Proxy.NO_PROXY)
            builder.connectTimeout(
                CONNECT_TIME_OUT,
                TimeUnit.MILLISECONDS
            )
            builder.readTimeout(
                READ_TIME_OUT,
                TimeUnit.MILLISECONDS
            )
            builder.writeTimeout(
                WRITE_TIME_OUT,
                TimeUnit.MILLISECONDS
            )
            //日志显示级别
            if (BuildConfig.DEBUG) {
                val level = HttpLoggingInterceptor.Level.BODY
                val loggingInterceptor = HttpLoggingInterceptor { message: String ->
                    UtilCommon.printLog(msg = message)
                }
                loggingInterceptor.level = level
                builder.addNetworkInterceptor(loggingInterceptor)
            }
            builder.retryOnConnectionFailure(true)
            builder.addInterceptor(Interceptor { chain ->
                val request = chain.request()
                val url: String = request.url.toString()
                chain.proceed(chain.request())
            })
            builder.build()
        }

        val apiService: ApiService by lazy {
            Retrofit.Builder()
                .baseUrl("https://www.baidu.com")
                .client(initOKHttpClient())
                .addCallAdapterFactory(ErrorHandlingCallAdapterFactory())
                .addConverterFactory(ScalarsConverterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build()
                .create(ApiService::class.java)
        }
    }
}